package com.zxd.interview.niosource.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  BioClientSocket 客户端 Socket实现
 * @author Xander
 * @version v1.0.0
 * @Package : com.zxd.interview.niosource.bio
 * @Description : BioClientSocket 客户端 Socket实现
 * @Create on : 2023/7/5 09:52
 **/
@Slf4j
public class BioClientSocket {


    public void initBIOClient(String host, int port) {
        BufferedReader reader = null;
        BufferedWriter writer = null;
        Socket socket = null;
        String inputContent;
        int count = 0;
        try {
            reader = new BufferedReader(new InputStreamReader(System.in));
            socket = new Socket(host, port);
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            log.info("clientSocket started: " + stringNowTime());
            while (((inputContent = reader.readLine()) != null) && count < 2) {
                inputContent = stringNowTime() + ": 第" + count + "条消息: " + inputContent + "\n";
                writer.write(inputContent);//将消息发送给服务端
                writer.flush();
                count++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
                reader.close();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public String stringNowTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date());
    }

    public static void main(String[] args) {
        BioClientSocket client = new BioClientSocket();
        client.initBIOClient("127.0.0.1", 8888);
    }/**
     运行结果：
     clientSocket started: 2023-07-05 10:26:05
     7978987
     797898
     tyuytu
     */
}
